package com.thientan.model

import com.thientan.model.core.AuditingInfo
import com.thientan.model.enums.TrangThaiHopDong
import com.thientan.utils.Constants

/**
 * Domain class used to represent entity from table HOP_DONG
 * @author DINH HONG CHAU
 *
 */
class HopDong {
	static embedded = ['auditingInfo']
	AuditingInfo auditingInfo

	static constraints = {
		auditingInfo(nullable: true)
		maHd(unique: true, maxSize: 10)
		nvDoiTruong(nullable: true)
		nvThuNgan(nullable: true)
		liDoTraHang(nullable: true, maxSize: 100)
		liDoGiamGia(nullable: true, maxSize: 100)
	}

	static mapping = {
		table 'HOP_DONG'
		id generator : 'increment'
		sort maHd : "asc"
		columns {
			id column : 'HOP_DONG_ID'
			maHd column : 'MA_HOP_DONG'
			nvDoiTruong column: 'DOI_TRUONG_ID'
			nvBan1 column: 'NHAN_VIEN1_ID'
			nvBan2 column: 'NHAN_VIEN2_ID'
			nvThuNgan column: 'NV_THU_NGAN_ID'
			khachHang column: 'KHACH_HANG_ID'
			daGiaoPhieu column: 'DA_GIAO_PHIEU', class: Boolean
		}
	}

	static transients = ["trangThaiText", "ngayBanText", "maDt", "maNv1", "maNv2", "maTn",
						 "khHoTen", "khDt", "khDchi", "khPxa", "khQhuyen", "khTpho"]
	static hasMany = [chiTietThuChis : ChiTietThuChi]

	Set<ChiTietThuChi> chiTietThuChis = []
	String maHd
	KhachHang khachHang
	NhanVien nvBan1
	NhanVien nvBan2
	NhanVien nvDoiTruong
	NhanVien nvThuNgan
	TrangThaiHopDong trangThai = TrangThaiHopDong.DANG_TRA_GOP
	Double giaTri
	Double tienTraTruoc
	Double tienDaThu
	Double tienConLai
	String liDoTraHang
	Date ngayBan
	Double tienGiamGia = 0
	String liDoGiamGia
	Integer dotBan
	boolean daGiaoPhieu = false

	// Transient properties and getters
	String maDt
	String maNv1
	String maNv2
	String maTn
	String khHoTen
	String khDt
	String khDchi
	String khPxa
	String khQhuyen
	String khTpho
	
	String getTrangThaiText() {
		return trangThai.displayText
	}

	String getNgayBanText() {
		new java.text.SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(ngayBan)
	}

	// Internal processes
	int updateTraGop(Double tienThuThem, Date ngayBan = null) {
		if (tienThuThem == 0 || tienThuThem > tienConLai) {
			return 1
		}
		tienDaThu += tienThuThem
		tienConLai -= tienThuThem
		if (tienConLai == 0) {
			trangThai = TrangThaiHopDong.KET_THUC
		}
		ChiTietThuChi cttc = new ChiTietThuChi([
					"nhanVien.id" : nvThuNgan.id,
					"soTien" : tienThuThem,
					"ngayLap" : ngayBan ?: new Date()
				])
		addToChiTietThuChis(cttc)
		return 0
	}

	void updateDenTraHang(TrangThaiHopDong trangThaiMoi) {
		trangThai = trangThaiMoi
		tienConLai = 0
	}
}
